local skynet = require "skynet"
local filelog = require "filelog"
local msghelper = require "agenthelper"
local playerdatadao = require "playerdatadao"
local table = table
require "enum"

local  MngPassword = {}

--[[
//请求管理密码
message MngPasswordReq {
	optional Version version = 1;
	optional string old_password = 2;  //旧密码
	optional string new_password = 3;  //新密码
	optional string new_password_confirm = 4; //新密码确认
}

//响应请求密码管理
message MngPasswordRes {
	optional int32 errcode = 1;
	optional string errcodedes = 2;
}
]]

function  MngPassword.process(session, source, fd, request)
	local responsemsg = {
		errcode = EErrCode.ERR_SUCCESS,
	}
	local server = msghelper:get_server()

	--检查当前登陆状态
	if not msghelper:is_login_success() then
		filelog.sys_error("MngPassword.process invalid server state", server.state)
		responsemsg.errcode = EErrCode.ERR_INVALID_REQUEST
		responsemsg.errcodedes = "无效的请求!"
		msghelper:send_resmsgto_client(fd, "MngPasswordRes", responsemsg)		
		return
	end

	if request == nil or request.old_password == nil 
		or request.new_password == nil or request.new_password_confirm == nil then
		filelog.sys_error("MngPassword.process invalid params")
		responsemsg.errcode = EErrCode.ERR_INVALID_REQUEST
		responsemsg.errcodedes = "无效的请求参数!"
		msghelper:send_resmsgto_client(fd, "MngPasswordRes", responsemsg)		
		return		
	end

	if request.new_password ~= request.new_password_confirm then
		responsemsg.errcode = EErrCode.ERR_TWO_NEWPASSWORD_NOTMATCH
		responsemsg.errcodedes = "确认新密码不正确!"
		msghelper:send_resmsgto_client(fd, "MngPasswordRes", responsemsg)		
		return
	end

	if msghelper:generate_zhuanzhang_password(request.old_password) ~= server.money.password then
		responsemsg.errcode = EErrCode.ERR_OLDPASSWORD_ERROR
		responsemsg.errcodedes = "您输入的老密码不正确!"
		msghelper:send_resmsgto_client(fd, "MngPasswordRes", responsemsg)		
		return
	end

	server.money.password = msghelper:generate_zhuanzhang_password(request.new_password)
	playerdatadao.save_player_money("update", server.rid, server.money)

	msghelper:send_resmsgto_client(fd, "MngPasswordRes", responsemsg)
end

return MngPassword

